package com.youmingxing.activity;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.youmingxing.BuildConfig;
import com.youmingxing.R;
import com.youmingxing.bean.Action;
import com.youmingxing.data.GlobalDataManager;
import com.youmingxing.dialog.UpdateDialog;
import com.youmingxing.fragment.AuditionFragment;
import com.youmingxing.fragment.ContentFragment;
import com.youmingxing.fragment.FocusFragment;
import com.youmingxing.fragment.SelfInfoFragment;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.GlobalDownloadManager;
import com.youmingxing.network.SelfInfoApi;
import com.youmingxing.utils.ListViewHightEvent;
import com.youmingxing.utils.LogUtil;
import com.youmingxing.utils.SharePreferenceUtil;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONObject;


/**
 * 主界面
 *
 * @author evilyin(ChenZhixi)
 * @since 15/9/1
 */
public class MainActivity extends BaseActivity {

    private FragmentTabHost mTabHost;
    private LayoutInflater mLayoutInflater;
    private Class fragmentList[] = {AuditionFragment.class, ContentFragment.class, FocusFragment.class, SelfInfoFragment.class};
    private String texts[] = {"活动", "广场", "关注", "我的"};
    private int mImageArray[] = {R.drawable.home_selector, R.drawable.square_selector, R.drawable
            .focus_selector, R.drawable.mine_selector};
    private long mExitTime;
    private boolean needPopup;
    private BroadcastReceiver receiver = null;
    Bundle bundle = new Bundle();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_main);
        performAction();
        mLayoutInflater = LayoutInflater.from(this);

        // 找到TabHost
        mTabHost = (FragmentTabHost) findViewById(R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        mTabHost.setBackgroundResource(R.color.grey_bg);
        mTabHost.getTabWidget().setDividerDrawable(null);

        // 得到fragment的个数
        int count = fragmentList.length;
        for (int i = 0; i < count; i++) {
            // 给每个Tab按钮设置图标、文字和内容
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(texts[i])
                    .setIndicator(getTabItemView(i));
            // 将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, fragmentList[i], null);
            // 设置Tab按钮的背景
//            mTabHost.getTabWidget().getChildAt(i)
//                    .setBackgroundResource(R.drawable.button_text_color);
        }
        needPopup = true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        performAction();
    }

    void performAction() {
        Intent intent = getIntent();
        Uri uri = intent.getData();
        if (uri != null) {
            String queryString = uri.getQuery();
            Action action = new Action(queryString.replace("action=", ""));
            action.jump(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        //        Uri uri = getIntent().getData();
//        if (uri != null) {
//            String actionStr = uri.getPath();
//            Action action = new Action(actionStr);
//            action.jump(this);
//        }
        if (GlobalDataManager.needSetMainTab) {
            setTab(0);
            GlobalDataManager.needSetMainTab = false;
            GlobalDataManager.save();
        }
        if (!needPopup) {
            return;
        }
        AllStarApi.getUpdateInfo(new BaseJsonHandler(this) {
            @Override
            public void onSuccessWithData(JSONObject response) {

                JSONObject upgrade = response.optJSONObject("data").optJSONObject("upgrade");
                JSONArray usermark = response.optJSONObject("data").
                        optJSONObject("usermark").optJSONArray("mark");
                LogUtil.i("-------usermark---", "" + usermark);
                SharePreferenceUtil sharePreferenceUtil = new SharePreferenceUtil(MainActivity.this);
                sharePreferenceUtil.setUsermark(usermark.toString());
                String serverVersion = upgrade.optString("version");
                GlobalDataManager.backgroundImg = response.optJSONObject("data").optString
                        ("background_img");
                GlobalDataManager.save();
                String currentVersion = BuildConfig.VERSION_NAME;
                if (!serverVersion.equals(currentVersion) && !serverVersion.isEmpty()) {
                    GlobalDataManager.needUpdate = true;
                    GlobalDataManager.save();
                    bundle.putInt("type", upgrade.optInt("style"));
                    bundle.putString("des", upgrade.optString("description"));
                    bundle.putString("link", upgrade.optString("link"));
                    switch (upgrade.optInt("style")) {
                        // 升级方式: 1强制; 2弹窗; 3设置里提醒
                        case 1:
                        case 2:
                            //判断activity是否被销毁
                            if (!MainActivity.this.isFinishing()) {
                                //showdialog fragment
                                showUpdateDialog();
                            }
                            break;
                        case 3:
                            break;
                        default:
                            break;
                    }
                } else {
                    GlobalDataManager.needUpdate = false;
                    GlobalDataManager.save();
                }
            }

            @Override
            public void onFail(int statusCode, String statusText) {
                LogUtil.i("-------onFail---", "onFail: " + statusCode);
                super.onFail(statusCode, statusText);
            }
        });

        SelfInfoApi.getMyNewsCount(new BaseJsonHandler(this) {
            @Override
            public void onSuccessWithData(JSONObject response) {
                JSONObject data = response.optJSONObject("data");
                int count = data.optInt("count");
                int auditionBadge = data.optInt("auditions_badge");
                int realAuthBadge = data.optInt("real_auth_badge");
                if (count > 0) {
                    setTabBadge(1, true);
                } else {
                    setTabBadge(1, false);
                }
                if (auditionBadge + realAuthBadge > 0) {
                    setTabBadge(3, true);
                } else {
                    setTabBadge(3, false);
                }
            }
        });
    }

    private boolean isShow = false;

    @Subscribe
    public void onEvent(ListViewHightEvent event) {
        isShow =event.isFinish;
    }

    public void showUpdateDialog() {
        initReceiver();
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        UpdateDialog dialog = new UpdateDialog();
        dialog.setArguments(bundle);
        dialog.setCancelable(false);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        dialog.show(ft, "UpdateDialog");
        needPopup = false;
    }

    public void setTab(int index) {
        mTabHost.setCurrentTab(index);
    }


    private View getTabItemView(int index) {
        View view = mLayoutInflater.inflate(R.layout.tab_item_view, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mImageArray[index]);
        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(texts[index]);

        return view;
    }

    public void setTabBadge(int index, boolean isVisible) {
        View view = mTabHost.getTabWidget().getChildAt(index);
        ImageView badge = (ImageView) view.findViewById(R.id.badge);
        if (isVisible) {
            badge.setVisibility(View.VISIBLE);
        } else {
            badge.setVisibility(View.GONE);
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 3000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initReceiver() {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //这里可以取得下载的id，这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听
                long finishedId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                if (finishedId == GlobalDataManager.downloadId) {
                    DownloadManager manager = GlobalDownloadManager.getInstance(MainActivity.this);
//                installApk(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
                    installApk(manager.getUriForDownloadedFile(finishedId));
                    unregisterReceiver(this);
                    hideDialog();
                    receiver = null;
                }
            }
        };
    }


    protected void installApk(Uri uri) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
//        EventBus.getDefault().unregister(this);
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
    }
}
